/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.security.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elsfs.cloud.common.core.vo.R;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 未认证，返回json格式的响应
 *
 * @author zeng
 */
@RequiredArgsConstructor
@Slf4j
public class JsonAuthenticationEntryPoint
    implements AuthenticationEntryPoint, ServerAuthenticationEntryPoint {
  private final ObjectMapper objectMapper;

  @Override
  public void commence(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
      throws IOException, ServletException {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    R<Object> errorData = R.error(exception.getMessage());
    if (exception instanceof InsufficientAuthenticationException authenticationException) {
      LOGGER.warn("未认证:" + request.getRequestURI(), authenticationException);
      errorData.setType(R.Type.invalid_token);
      errorData.setMessage(authenticationException.getLocalizedMessage());
    }
    if (exception instanceof InvalidBearerTokenException) {
      // An error occurred while attempting to decode the Jwt: Jwt expired
      errorData.setMessage("token 已经过期");
      errorData.setType(R.Type.invalid_token);
    }
    var outputStream = response.getOutputStream();
    outputStream.write(objectMapper.writeValueAsString(errorData).getBytes(StandardCharsets.UTF_8));
    outputStream.flush();
  }

  @Override
  public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException exception) {
    return Mono.defer(
        () -> {
          ServerHttpResponse response = exchange.getResponse();
          ServerHttpRequest request = exchange.getRequest();
          R<Object> errorData = R.error(exception.getMessage());
          response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
          if (exception instanceof InsufficientAuthenticationException authenticationException) {
            LOGGER.warn("未认证:" + request.getURI(), authenticationException);
            errorData.setMessage(authenticationException.getLocalizedMessage());
          }
          try {
            return response.writeWith(
                Mono.just(
                    response
                        .bufferFactory()
                        .wrap(
                            objectMapper
                                .writeValueAsString(errorData)
                                .getBytes(StandardCharsets.UTF_8))));
          } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
          }
        });
  }
}
